package com.chaochis.springboottestdemo.config.jacksonConfig.deserialzation;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;

public class BaseEnumDeserialization extends JsonDeserializer<Enum> {
  @Override
  public Enum deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    var result = (Enum) null;
    try {
      var parseType = jsonParser.getParsingContext().getCurrentValue().getClass().getDeclaredField(jsonParser.getCurrentName()).getType();
      var valuesMethod = parseType.getDeclaredMethod("values");
      var invokeObj = ((Object[])valuesMethod.invoke(this))[0];
      var parseMethod = parseType.getDeclaredMethod("getEnumFromValue", String.class);
      result = (Enum) parseMethod.invoke(invokeObj, jsonParser.getText());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
}
